package com.hgs.iias.domain;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;

import org.acegisecurity.GrantedAuthority;
import org.acegisecurity.userdetails.UserDetails;

import com.googlecode.jsonplugin.annotations.JSON;

@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@Table(name = "iias_users")
public class User extends DomainObject implements UserDetails {
	private static final long serialVersionUID = 6160267833598682873L;
	
	public static final String PASSWORD = "password";
	public static final String CONFIRM  = "confirm"; 
	
	@Basic
	@Column(nullable = false, length = 32)
	private String password;
	
	@Basic
	@Column(nullable = false)
	private boolean enabled;
	
	@Basic
	private String email;
	
	@Basic
	private String remark;
	
	@ManyToMany
	@JoinTable(name = "iias_users_roles")
	private List<Role> roles;
	
	public String getEmail() {
		return email;
	}
	
	public void setEmail(String email) {
		this.email = email;
	}
	
	public boolean isEnabled() {
		return enabled;
	}
	
	public void setEnabled(boolean enabled) {
		this.enabled = enabled;
	}
	
	public String getPassword() {
		return password;
	}
	
	public void setPassword(String password) {
		this.password = password;
	}
	
	public String getRemark() {
		return remark;
	}
	
	public void setRemark(String remark) {
		this.remark = remark;
	}
	
	public List<Role> getRoles() {
		if(roles == null) {
			setRoles(new ArrayList<Role>());
		}
		
		return roles;
	}
	
	public void setRoles(List<Role> roles) {
		this.roles = roles;
	}
	
	@JSON(serialize = false)
	public GrantedAuthority[] getAuthorities() {
		return getRoles().toArray(new GrantedAuthority[0]);
	}
	
	@JSON(serialize = false)
	public String getUsername() {
		return getId();
	}
	
	@JSON(serialize = false)
	public boolean isAccountNonExpired() {
		return isEnabled();
	}
	
	@JSON(serialize = false)
	public boolean isAccountNonLocked() {
		return isEnabled();
	}
	
	@JSON(serialize = false)
	public boolean isCredentialsNonExpired() {
		return isEnabled();
	}
	
	public void addRole(Role role) {
		getRoles().add(role);
	}
}
